package com.zy.chapter1;

import java.util.Iterator;

/**
 * 支持泛型的背包 链表实现
 * @author zhangyi
 *
 * @param <Item>
 */
public class Bag<Item> implements Iterable<Item>{
	
	private int n=0;
	
	private Node first;//链表首节点
	
	public boolean isEmpty(){
		return n==0;
	}
	
	public int size(){
		return n;
	}
	
	
	/**
	 * 栈式的方式 后入先出
	 * @param item
	 */
	public void add(Item item){
		Node oldFirst = first;
		first = new Node();
		first.item = item;
		first.next = oldFirst;
		n++;
	}
	
	@Override
	public Iterator<Item> iterator() {
		// TODO Auto-generated method stub
		return new ListIterator();
	}
	
	/**
	 * 迭代器
	 * @author zhangyi
	 *
	 */
	private class ListIterator implements Iterator<Item>{
		
		private Node current = first;
		
		@Override
		public boolean hasNext() {
			// TODO Auto-generated method stub
			return current != null;
		}

		@Override
		public Item next() {
			// TODO Auto-generated method stub
			Item item = current.item;
			current = current.next;
			return item;
		}
		
	}
	
	/**
	 * 链表节点内部类
	 * @author zhangyi
	 *
	 */
	private class Node{
		Item item;
		Node next;
	}
}
